use crate::config::app_config::AppConfig;
use crate::config::database_config::DatabaseConfig;
use crate::config::log_config::LogConfig;
use crate::config::thread_pool_config::ThreadPoolConfig;
use crate::model::thread_local_var::ThreadLocalVar;
use crate::test::example;
use crate::utils::thread::wait_task_completed;
use chrono::Local;
use lazy_static::lazy_static;
use rbatis::RBatis;
use std::cell::RefCell;
use tokio::runtime::Runtime;

mod config;
mod model;
mod test;
mod utils;

lazy_static! {
    /// 懒加载静态对象 运行时初始化
    /// 加载配置文件
    pub static ref APP_CONFIG: AppConfig = AppConfig::load();
    /// 初始化redis连接url
    pub static ref REDIS_URL: String = APP_CONFIG.redis.get_url();
    /// 初始化数据库连接池
    pub static ref RBATIS: RBatis = DatabaseConfig::init_connect_pool();
    /// 初始化公共线程池
    pub static ref EXECUTOR: Runtime = ThreadPoolConfig::init_thread_pool();
}

thread_local! {
    /// 线程绑定变量
    pub static THREAD_LOCAL_VAR: RefCell<ThreadLocalVar> = RefCell::new(Default::default());
}

#[tokio::main(flavor = "multi_thread", worker_threads = 5)]
async fn main() {
    let start = Local::now();
    init_required();

    example::test_string();
    example::test_hash();
    example::test_zsort();

    example::test_sql().await;
    example::test_sql_sync();

    destroy().await;
    log::info!(
        "耗时：{:?}ms!",
        Local::now().timestamp_millis() - start.timestamp_millis()
    )
}

/// 初始化系统相关资源
fn init_required() {
    // 初始化日志配置
    LogConfig::load_log4rs();

    log::info!("系统资源初始化完成！");
}

/// 销毁系统资源
async fn destroy() {
    // 等待线程池任务执行完成
    wait_task_completed().await;
}
